package com.dynamic.idea.quick.develop.plugin.dialog;

import com.alibaba.fastjson.JSON;
import com.dynamic.idea.quick.develop.plugin.constants.QuickDevelopConstants;
import com.dynamic.idea.quick.develop.plugin.entity.ProjectStructEntity;
import com.dynamic.idea.quick.develop.plugin.entity.base.MethodEntity;
import com.dynamic.idea.quick.develop.plugin.entity.base.ParamEntity;
import com.dynamic.idea.quick.develop.plugin.entity.base.ProjectStructProviderEntity;
import com.dynamic.idea.quick.develop.plugin.entity.base.ProjectStructProviderImplEntity;
import com.dynamic.idea.quick.develop.plugin.utils.NotifyUtils;
import com.dynamic.idea.quick.develop.plugin.utils.PsiClassUtils;
import com.intellij.ide.highlighter.JavaClassFileType;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.*;
import com.intellij.psi.*;
import com.intellij.psi.impl.file.PsiDirectoryFactory;
import com.intellij.psi.impl.file.PsiJavaDirectoryFactory;
import com.intellij.psi.impl.source.tree.PsiWhiteSpaceImpl;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.javadoc.PsiDocTag;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.util.ui.UI;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.model.Model;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Deprecated
public class QuickDevelopStartDialogWrapper extends DialogWrapper {

    private Project project;

    // 文本输入框大小
    private static final int FIELD_SIZE=30;

    // maven的pom文件
    private Model mavenModel=null;

    // 类名
    private JTextField classNameJTextField =null;

    // 基础包名
    private JTextField basePackageJTextField =null;

    // 方法名
    private JTextField methodNameJTextField =null;

    // 请求参数
    private JTextField requestParamJTextField =null;

    // 返回参数
    private JTextField returnParamJTextField =null;

    // 方法说明
    private JTextField annotationJTextField =null;


    public QuickDevelopStartDialogWrapper(Project project) {
        super(true); // use current window as parent
        this.project=project;

        setTitle("Quick Develop Starting");
        String basePath = project.getBasePath();

//        String pomPath=basePath+"/pom.xml";
//
//        mavenModel= ModulesUtils.getMavenModel(pomPath);

        init();
    }

    @Nullable
    @Override
    protected JComponent createCenterPanel() {
        //类名
        classNameJTextField =new JTextField(FIELD_SIZE);
        //基础包名
//        basePackageJTextField =new JTextField(FIELD_SIZE);

        //方法名
        methodNameJTextField =new JTextField(FIELD_SIZE);
        //请求参数
        requestParamJTextField =new JTextField(FIELD_SIZE);

        //返回参数
        returnParamJTextField =new JTextField(FIELD_SIZE);

        //方法注释
        annotationJTextField =new JTextField(FIELD_SIZE);


        //测试数据
        classNameJTextField.setText("BillOrder2");

//        basePackageJTextField.setText("cn.sdpjw.order");

        methodNameJTextField.setText("saveTest");

        requestParamJTextField.setText("String a");

        returnParamJTextField.setText("String");

        annotationJTextField.setText("这是一段自动生成代码的测试示例");

        JPanel p = UI.PanelFactory.grid()
                .add(UI.PanelFactory.panel(classNameJTextField).withLabel("className:"))
//                .add(UI.PanelFactory.panel(classNameJTextField).withLabel("basePackage:"))
                .add(UI.PanelFactory.panel(methodNameJTextField).withLabel("methodName:"))
                .add(UI.PanelFactory.panel(requestParamJTextField).withLabel("requestParam:"))
                .add(UI.PanelFactory.panel(returnParamJTextField).withLabel("returnParam:"))
                .add(UI.PanelFactory.panel(annotationJTextField).withLabel("docComment:"))
                .createPanel();

        return p;
    }

    @Override
    protected void doOKAction() {
        super.doOKAction();

        String basePath=project.getBasePath();

        ProjectStructEntity projectStructEntity=new ProjectStructEntity();

        ProjectStructProviderImplEntity providerImplEntity=new ProjectStructProviderImplEntity();

        providerImplEntity.setBasePackageName("cn.sdpjw.order");
        providerImplEntity.setClassName(classNameJTextField.getText());
        providerImplEntity.setProjectName("order-service");
        providerImplEntity.setBasePath(basePath);


        ProjectStructProviderEntity providerEntity=new ProjectStructProviderEntity();
        providerEntity.setBasePath(basePath);
        providerEntity.setBasePackageName("cn.sdpjw.order.stub");
        providerEntity.setClassName(classNameJTextField.getText());
        providerEntity.setProjectName("order-stub");

        projectStructEntity.setProviderImplEntity(providerImplEntity);
        projectStructEntity.setProviderEntity(providerEntity);

        // 方法
        MethodEntity methodEntity =new MethodEntity();

        // 方法名
        methodEntity.setName(methodNameJTextField.getText());

        // 请求参数
        String requestParamJTextFieldText = requestParamJTextField.getText();

        // 方法注释
        String docCommentJTextFieldText = annotationJTextField.getText();

        docCommentJTextFieldText="/** \n* "+docCommentJTextFieldText+"\n*/";

        List<ParamEntity> paramList=new ArrayList<>();
        ParamEntity paramEntity=new ParamEntity();
        paramEntity.setClassName(StringUtils.substringBefore(requestParamJTextFieldText," "));
        paramEntity.setVariableName(StringUtils.substringAfterLast(requestParamJTextFieldText," "));

        paramList.add(paramEntity);
        methodEntity.setParamList(paramList);

        methodEntity.setDocComment(docCommentJTextFieldText);

        // 返回参数
        ParamEntity returnParamEntity=new ParamEntity();
        returnParamEntity.setClassName(returnParamJTextField.getText());
        methodEntity.setReturnParam(returnParamEntity);

        projectStructEntity.setMethodEntity(methodEntity);

//        System.out.println(JSON.toJSONString(projectStructEntity,true));

        // 生成
        GlobalSearchScope projectSearchScope=GlobalSearchScope.projectScope(project);
        GlobalSearchScope allSearchScope=GlobalSearchScope.allScope(project);

        WriteCommandAction.runWriteCommandAction(project, new Runnable() {

            @Override
            public void run() {
                PsiClass providerClass = JavaPsiFacade.getInstance(project).findClass(providerEntity.getProviderClassFullName(),projectSearchScope);
                System.out.println("providerClass:"+providerClass);


                boolean isContainMethod = PsiClassUtils.containMethod(providerClass, methodEntity.getName());
                System.out.println("isContainMethod:"+isContainMethod+",methodEntity.getName():"+methodEntity.getName());

                PsiDirectoryFactory psiDirectoryFactory = PsiJavaDirectoryFactory.getInstance(project);
                PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
                // 不存在class,则创建class
                boolean isNewClass=false;
                if (providerClass==null){
                    try {
                        isNewClass=true;
                        VirtualFile virtualFile = null;
                        try {
                            providerClass = factory.createInterface(providerEntity.getProviderClassName());

                            virtualFile = VfsUtil.createDirectoryIfMissing(providerEntity.getProviderPath());
                            PsiDirectory directory = psiDirectoryFactory.createDirectory(virtualFile);
                            directory.add(providerClass);
                            System.out.println(virtualFile);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    providerClass = JavaPsiFacade.getInstance(project).findClass(providerEntity.getProviderClassFullName(), projectSearchScope);
                }
                // 若包含则覆盖更新
                if (isContainMethod){
                    PsiClassUtils.removeMethod(providerClass,methodEntity.getName());
                }

//                System.out.println(JSON.toJSONString(providerClass,true));

                String valueAllName="CommonResponse<LocalDateTime>";
                PsiType valuePsiType = factory.createTypeFromText(valueAllName, providerClass);

                PsiMethod methodPsiMethod = factory.createMethod(methodEntity.getName(), valuePsiType);
                // 删除body体 只留声明
                methodPsiMethod.getBody().delete();

                PsiParameterList parameterList = methodPsiMethod.getParameterList();

                PsiParameter descPsiParameter = factory.createParameterFromText(requestParamJTextField.getText(), providerClass);
                parameterList.add(descPsiParameter);

                // 加注释
                PsiDocComment psiComment = factory.createDocCommentFromText(methodEntity.getDocComment(),methodPsiMethod);

                // 增加参数注释
                psiComment.add(factory.createParamTag("a","测试参数1"));
                // 增加返回注释
                psiComment.add(factory.createDocTagFromText("@return"));

                methodPsiMethod.addBefore(psiComment,methodPsiMethod.getFirstChild());
                providerClass.add(methodPsiMethod);

                // 检查新方法的请求与返回值是否存在未导入的包
                PsiFile psiFile = providerClass.getContainingFile();
                if (psiFile instanceof PsiJavaFile){
                    PsiJavaFile javaFile = (PsiJavaFile)psiFile;
                    PsiImportList importList = javaFile.getImportList();
                    if (importList!=null){
                        PsiImportStatement singleClassImportStatement = importList.findSingleClassImportStatement("java.time.LocalDateTime");
                        if (singleClassImportStatement == null){
//                            PsiImportStatement psiImportStatement = factory.createImportStatement(providerClass);
                            PsiClass importPsiClass = JavaPsiFacade.getInstance(project).findClass("java.time.LocalDateTime", allSearchScope);

                            PsiImportStatement importStatement = factory.createImportStatement(importPsiClass);
                            importList.add(importStatement);
                        }

                        // CommonResponse
                        PsiImportStatement commonResponseClassImportStatement = importList.findSingleClassImportStatement("cn.sdpjw.common.base.response.CommonResponse");
                        if (commonResponseClassImportStatement == null){
                            PsiClass importPsiClass = JavaPsiFacade.getInstance(project).findClass("cn.sdpjw.common.base.response.CommonResponse", allSearchScope);
                            PsiImportStatement importStatement = factory.createImportStatement(importPsiClass);
                            importList.add(importStatement);
                        }
                    }
                }

                //若是新文件 则添加新文件到目录下
//                if (isNewClass){
//                    VirtualFile virtualFile = null;
//                    try {
//                        virtualFile = VfsUtil.createDirectoryIfMissing(providerEntity.getProviderPath());
//                        PsiDirectory directory = psiDirectoryFactory.createDirectory(virtualFile);
//                        directory.add(providerClass);
//                        System.out.println(virtualFile);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }

            }
        });
        NotifyUtils.notifyInfo("quick develop success");

    }

}
